<script setup lang='ts'>
import { ComponentInternalInstance, getCurrentInstance, ref, toRaw, watch } from 'vue';
import { classList, collegeList, delStudents, getStu, getStudents, resetStudents } from '@/api/axios/studentsAxios';
import { ElMessage, ElMessageBox, UploadProps } from 'element-plus';
import { useRouter } from 'vue-router';
import type { FormInstance } from 'element-plus';

import { UploadFilled } from '@element-plus/icons-vue';
import { getToken } from '@/utils/auth';
import { download, downloadJson } from '@/utils/request';
import router from '@/router';

const border = ref(true);

const dialogVisible = ref(false);

const info = ref('');

const stuList = ref({
    pageNum: 1,
    pageSize: 10,
    name: '',
    collegeId: '',
    classId: '',
    stuNum: '',
    phoneNumber: '',
    grade: '',
    className: '',
    psychometricTest: ''
});

const total = ref(0);

function initStu() {
    getStudents(stuList.value).then(res => {
        // console.log(res.rows);
        tableData.value = res.rows;
        total.value = res.total;

        tableData.value.map(item => {
            // console.log(item.className);
            if (item.classId === '') {
                item.className = '暂无数据';
            }
            return item.className;
        });
    });
}

// 学院
const collegeOptions = ref([]);
collegeList().then(res => {
    // console.log(res.data);
    collegeOptions.value = res.data;
    classData.value.deptId = res.data.deptId;
});

// 班级
const classData = ref({
    deptId: '',
    name: ''
});
const classOptions = ref([]);
classList(classData.value).then(res => {
    // console.log(res);
    classOptions.value = res.rows;
});

watch(() => stuList.value.collegeId, () => {
    classData.value.deptId = stuList.value.collegeId;
    classList(classData.value).then(res => {
        console.log(res);
        classOptions.value = res.rows;
    });
});

const tableData = ref([]);
initStu();
// import { ElTable } from 'element-plus'

// interface User {
//     date: string
//     name: string
//     address: string
// }

// const multipleTableRef = ref<InstanceType<typeof ElTable>>()
// const multipleSelection = ref<User[]>([])
//
// const handleSelectionChange = (val: User[]) => {
//     multipleSelection.value = val
// }

// 搜索
function search() {
    tableData.value.map(item => {
        // console.log(item.className);
        if (item.className === stuList.value.className) {
            stuList.value.classId = item.classId
        }
    })
    console.log(stuList.value);
    initStu();
}

// 重置
function reset() {
    stuList.value = {
        pageNum: 1,
        pageSize: 10,
        name: '',
        collegeId: '',
        classId: '',
        stuNum: '',
        phoneNumber: '',
        grade: '',
        className: ''
    };
    initStu();
}

const onPageChange = (e) => {
    stuList.value.pageNum = e;
    initStu();
};

const regex = /^[1][3,4,5,7,8][0-9]{9}$/;

function leave() {
    if (regex.test(stuList.value.phoneNumber)) {
        console.log('xxx');
    }
}

const form = ref({});

function addStu() {
    form.value = {};
    dialogVisible.value = true;
}

function handleSave(value) {
    // 刷新列表
    ElMessage({
        showClose: true,
        message: '操作成功',
        type: 'success'
    });
    initStu();
}

// 编辑
function edit(data) {
    // console.log(data);
    form.value = toRaw(data);
    dialogVisible.value = true;
    // form.value.name = data.name
}


// 普测弹窗
const testVisible = ref(false);

function testInfo(data) {
    testVisible.value = true;
    stuList.value.psychometricTest = data.psychometricTest;
}

// 删除
const del = (data) => {
    console.log(data);
    let id = String(data.id);
    ElMessageBox.confirm(
        '此操作将永久删除该学生信息，是否继续？',
        '提示',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning'
        }
    )
        .then(() => {
            delStudents([id]).then(res => {
                console.log(res);
                ElMessage({
                    type: 'success',
                    message: '删除成功'
                });
                initStu();
            });

        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除'
            });
        });
};

const uploadVisible = ref(false);

// 导入
function upload() {
    uploadVisible.value = true;
}


// 重置密码 resetPsw
const studentId = ref('');
const resetPsw = (data) => {
    console.log(data);
    studentId.value = data.id;
    ElMessageBox.confirm(
        '此操作将重置学生密码为学号，是否继续？',
        '提示',
        {
            confirmButtonText: '重置',
            cancelButtonText: '取消',
            type: 'warning'
        }
    )
        .then(() => {
            resetStudents({ studentId: studentId.value }).then(res => {
                console.log(res);

                ElMessage({
                    type: 'success',
                    message: '修改成功，新密码为该学生学号'
                });

            });
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消修改'
            });
        });
};

// 心理档案
// const router = useRouter();

function psyInfo(data) {
    router.push({ path: '/record' , query: data });
}

// 导入
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadUrl = baseUrl + '/system/student/import';
const header = {
    'Authorization': 'Bearer ' + getToken()
};
// 判断导入格式
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.name.toLowerCase().split('.').pop() !== 'xlsx') {
        ElMessage.error('文件必须是xlsx格式!');
        return false;
    }
    return true;
};


const handleSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    if (response.code === 200) {
        ElMessage.success(response.msg);
    } else {
        ElMessage.error(response.msg);
    }
};

// 部分导出

const disabled = ref(true)
const selArr = ref([])
const handleSelectionChange = (newSelection: any[]) => {
    if(newSelection) {
        disabled.value = false
    }
    console.log(newSelection)
    newSelection.map(item => {
        selArr.value.push(item.id)
    })
    console.log(selArr.value);
}

function handleExport() {
    downloadJson(
        '/system/student/partExport',
        selArr.value,
        `student_${new Date().getTime()}.xlsx`
    );
}

const stuArr = ref([])
getStu().then(res => {
    // console.log(res.rows);
    res.rows.map(item => {
        stuArr.value.push(item.id)
    })
})
// console.log(stuArr);
function allExport() {
    downloadJson(
        '/system/student/partExport',
        stuArr.value,
        `student_${new Date().getTime()}.xlsx`
    );
}


</script>

<template>
    <div>
        <ul class='gap-4 mb-4 items-center stuForm'>
            <li>
                <!--            姓名-->
                <span style='margin-right: 15px;font-size: 14px;'><b>姓名</b></span>
                <el-input
                    v-model='stuList.name'
                    style='width: 243px;'
                    size='large'
                    placeholder='请输入姓名'
                />
            </li>
            <li>
                <!--            学院-->
                <span style='margin-right:15px;font-size: 14px;'><b>学院</b></span>
                <el-select
                    v-model='stuList.collegeId'
                    placeholder='请选择学院'
                    size='large'
                    style='width: 243px;'
                >
                    <el-option
                        v-for='item in collegeOptions'
                        :key='item.deptId'
                        :label='item.deptName'
                        :value='item.deptId'
                    />
                </el-select>
            </li>
            <li>
                <!--            年级-->
                <span style='margin-right: 15px;font-size: 14px;'><b>年级</b></span>
                <el-input
                    v-model='stuList.grade'
                    style='width: 243px;'
                    size='large'
                    placeholder='请输入年级'
                />
            </li>
            <li>
                <!--            班级-->
                <span style='margin-right: 10px;font-size: 14px;'><b>班级</b></span>
                <el-select
                    v-model='stuList.className'
                    placeholder='请选择班级'
                    size='large'
                    style='width: 243px;'
                >
                    <el-option
                        v-for='item in classOptions'
                        :key='item.id'
                        :label='item.name'
                        :value='item.name'
                    />
                </el-select>
            </li>
            <li>
                <!--            学号-->
                <span style='margin-right: 15px;font-size: 14px;'><b>学号</b></span>
                <el-input
                    v-model='stuList.stuNum'
                    style='width: 243px;'
                    size='large'
                    placeholder='请输入学号'
                />
            </li>
            <li>
                <!--            手机号-->
                <span style='margin-right: 15px;font-size: 14px;'><b>手机号</b></span>
                <el-input
                    v-model='stuList.phoneNumber'
                    style='width: 243px;'
                    size='large'
                    placeholder='请输入手机号'
                    @focus='leave'
                    validate-event
                />
            </li>
            <li style='margin-left: 50px;'>
                <el-button size='large' @click='reset'>重置</el-button>
                <el-button type='primary' size='large' @click='search'>搜索</el-button>
            </li>
        </ul>
        <div class='stuBtn'>
            <el-button type='primary' size='large' @click='addStu'>添加</el-button>
            <el-button type='primary' size='large' @click='upload'>导入</el-button>
            <el-button type='primary' size='large' :disabled='disabled' @click='handleExport'>导出</el-button>
            <el-button type='primary' size='large' @click='allExport'>全部导出</el-button>
        </div>
        <div>
            <el-table :data='tableData' :border=border style='width: 95%;margin: 0 auto'
                      ref='multipleTableRef'
                      @selectionChange='handleSelectionChange'
                      cell-class-name='cellBox'
            >
                <el-table-column type='selection' width='48' align='center' />
                <el-table-column type='index' label='序号' width='86' align='center' />
                <el-table-column prop='name' label='姓名' align='center' width='126' />
                <el-table-column prop='college' label='学院' align='center' width='126' />
                <el-table-column prop='grade' label='年级' width='86' align='center' />
                <el-table-column prop='className' label='班级' width='126' align='center' />
                <el-table-column prop='stuNum' label='学号' align='center' />
                <el-table-column prop='phoneNumber' label='手机号' align='center' />
                <el-table-column prop='createTime' label='入学日期' align='center' />
                <el-table-column fixed='right' label='操作' width='240' align='center'>
                    <template v-slot='scope'>
                        <el-button link type='primary' @click='edit(scope.row)'>
                            <el-icon>
                                <EditPen />
                            </el-icon>
                            编辑
                        </el-button>
                        <el-button link type='primary' @click='testInfo(scope.row)'>
                            <el-icon>
                                <Document v-model='stuList.psychometricTest' />
                            </el-icon>
                            普测信息
                        </el-button>
                        <el-button link type='primary' @click='del(scope.row)'>
                            <el-icon>
                                <Delete />
                            </el-icon>
                            删除
                        </el-button>
                        <br>
                        <el-button link type='primary' @click='psyInfo(scope.row)'>
                            <el-icon>
                                <Paperclip />
                            </el-icon>
                            心理档案
                        </el-button>
                        <el-button link type='primary' @click='resetPsw(scope.row)'>
                            <el-icon>
                                <Key />
                            </el-icon>
                            重置密码
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class='pageNum'>
            <el-pagination background layout='prev, pager, next' :total='total'
                           v-model:page-size='stuList.pageSize' v-model:current-page='stuList.pageNum'
                           @currentChange='onPageChange' />
        </div>
    </div>

    <students-dialog v-model:visible='dialogVisible' :stuInfo='form' @handleSave='handleSave'></students-dialog>

    <!--    普测信息-->
    <el-dialog
        v-model='testVisible'
        title='普测信息'
        width='700'
    >
        <div>
            <el-input
                v-model='info'
                style='width: 100%'
                maxlength='300'
                placeholder='请输入其他
'
                show-word-limit
                type='textarea'
                resize='none'
                rows='13'
            />
        </div>
        <template #footer>
            <div class='dialog-footer'>
                <el-button @click='testVisible = false' size='large'>取消</el-button>
                <el-button type='primary' @click='testVisible = false' size='large'>
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!--    导入  -->
    <el-dialog
        v-model='uploadVisible'
        title='Tips'
        width='402'
    >
        <div>
            <el-upload
                class='upload-demo'
                drag
                :action='uploadUrl'
                method='post'
                :headers='header'
                :on-success='handleSuccess'
                :before-upload='beforeUpload'
                :show-file-list='false'
            >
                <el-icon class='el-icon--upload'>
                    <upload-filled />
                </el-icon>
                <div class='el-upload__text'>
                    将文件拖到此处,或<em>点此上传</em>
                </div>
                <template #tip>
                    <div class='el-upload__tip'>
                        仅允许导入xlsx格式文件。
                    </div>
                </template>
            </el-upload>
        </div>
        <template #footer>
            <div class='dialog-footer'>
                <el-button @click='uploadVisible = false' size='large'>取消</el-button>
                <el-button type='primary' @click='uploadVisible = false' size='large'>
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped lang='scss'>
.gap-4 {
    padding: 26px 25px;
    width: 100%;
    margin-left: 20px;
}

.stuForm {
    display: flex;
    flex-wrap: wrap;

    li {
        margin-right: 20px;
    }
}

.stuBtn {
    padding: 0 25px 15px;
}

div.cell {
    //height: 36px;
    font-size: 14px;
    //line-height: 36px;
    padding: 9px 0 !important;
}

.pageNum {
    margin-top: 25px;
    float: right;
    margin-right: 50px;
}

.cellBox {
    text-align: center;
}

//.el-dialog__header {
//    background-color: #1892ff;
//    margin-right: 0;
//
//    .el-dialog__title {
//        font-size: 18px;
//        color: #fff;
//    }
//
//    .el-dialog__headerbtn .el-dialog__close {
//        color: #fff !important;
//    }
//}
</style>
